<template>
  <div class="appeal-container">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane :label="isAdmin ? '所有申诉记录' : '我的申诉记录'" name="records">
        <el-card shadow="hover" class="appeal-card">
          <template #header>
            <div class="card-header">
              <span>{{ isAdmin ? '所有申诉记录' : '我的申诉记录' }}</span>
              <el-button v-if="!isAdmin" type="primary" @click="handleCreateAppeal">发起申诉</el-button>
            </div>
          </template>

          <el-table :data="appealRecords" v-loading="loading" border style="width: 100%">
            <el-table-column prop="id" label="申诉ID" width="80" />
            <el-table-column prop="violationId" label="违法记录ID" width="120" />
            <el-table-column prop="violation_type" label="违法类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getViolationTypeTag(row.violation_type)">
                  {{ getViolationTypeName(row.violation_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="违法地点" width="180" show-overflow-tooltip />
            <el-table-column prop="reason" label="申诉理由" min-width="200" show-overflow-tooltip />
            <el-table-column prop="create_time" label="申诉时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="审核状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">
                  {{ getStatusName(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleViewDetail(row)">查看详情</el-button>
                <!-- 管理员操作按钮 -->
                <template v-if="isAdmin && row.status === '0'">
                  <el-button type="success" link @click="handleApprove(row)">通过</el-button>
                  <el-button type="danger" link @click="handleReject(row)">驳回</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane v-if="!isAdmin" label="发起申诉" name="create">
        <el-card shadow="hover" class="appeal-card">
          <template #header>
            <div class="card-header">
              <span>发起申诉</span>
            </div>
          </template>

          <el-form :model="appealForm" :rules="rules" ref="appealFormRef" label-width="120px">
            <el-form-item label="违法记录ID" prop="violation_id">
              <el-select v-model="appealForm.violation_id" placeholder="请选择违法记录" filterable
                @change="handleViolationChange">
                <el-option v-for="item in violationOptions" :key="item.id"
                  :label="`${item.id} - ${getViolationTypeName(item.violation_type)}`" :value="item.id">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>{{ item.id }}</span>
                    <span>{{ getViolationTypeName(item.violation_type) }}</span>
                    <span>{{ formatDateTime(item.create_time) }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="违法类型">
              <el-tag :type="getViolationTypeTag(selectedViolation.violation_type)">
                {{ getViolationTypeName(selectedViolation.violation_type) }}
              </el-tag>
            </el-form-item>

            <el-form-item label="违法地点">
              <span>{{ selectedViolation.location || '无' }}</span>
            </el-form-item>

            <el-form-item label="违法时间">
              <span>{{ selectedViolation.create_time ? formatDateTime(selectedViolation.create_time) : '无'
                }}</span>
            </el-form-item>

            <el-form-item label="违法图片" v-if="selectedViolation.image_path">
              <el-image :src="selectedViolation.image_path" style="width: 200px; height: 150px"
                :preview-src-list="[selectedViolation.image_path]" />
            </el-form-item>

            <el-form-item label="申诉理由" prop="reason">
              <el-input v-model="appealForm.reason" type="textarea" :rows="4" placeholder="请详细描述申诉理由" />
            </el-form-item>

            <el-form-item label="申诉材料" prop="file">
              <el-upload class="appeal-upload" action="/api/upload" :on-success="handleUploadSuccess"
                :on-error="handleUploadError" :before-upload="beforeUpload" :limit="5" multiple>
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传申诉相关证明材料，支持jpg/png/pdf格式，单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitAppealForm">提交申诉</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 申诉详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申诉详情" width="60%">
      <div class="appeal-detail" v-if="currentAppeal.id">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申诉ID">{{ currentAppeal.id }}</el-descriptions-item>
          <el-descriptions-item label="违法记录ID">{{ currentAppeal.violation_id }}</el-descriptions-item>
          <el-descriptions-item label="违法类型">
            <el-tag :type="getViolationTypeTag(currentAppeal.violation_type)">
              {{ getViolationTypeName(currentAppeal.violation_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申诉时间">{{ formatDateTime(currentAppeal.create_time)
            }}</el-descriptions-item>
          <el-descriptions-item label="违法地点" :span="2">{{ currentAppeal.location }}</el-descriptions-item>
          <el-descriptions-item label="申诉理由" :span="2">{{ currentAppeal.reason }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusTag(currentAppeal.status)">
              {{ getStatusName(currentAppeal.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="currentAppeal.update_time">
            {{ formatDateTime(currentAppeal.update_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="处理意见" :span="2" v-if="currentAppeal.detail">
            {{ currentAppeal.detail }}
          </el-descriptions-item>
          <el-descriptions-item label="申诉材料" :span="2" v-if="currentAppeal.file">
            <div class="appeal-files">
              <el-image v-for="(file, index) in parseFiles(currentAppeal.file)" :key="index" :src="file"
                :preview-src-list="parseFiles(currentAppeal.file)" fit="cover" class="appeal-file-image" />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="违法图片" :span="2" v-if="currentAppeal.image_path">
            <el-image :src="currentAppeal.image_path" style="width: 200px; height: 150px"
              :preview-src-list="[currentAppeal.image_path]" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 处理申诉对话框 -->
    <el-dialog v-model="processDialogVisible" :title="processType === 'approve' ? '通过申诉' : '驳回申诉'" width="40%">
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="处理意见" prop="detail">
          <el-input v-model="processForm.detail" type="textarea" :rows="4" placeholder="请输入处理意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/date'
import { getUserAppealPage, submitAppeal, getAppealPage, processAppeal ,getAppealByid} from '@/api/appeal'
import { getViolationPage } from '@/api/violation'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
// 根据用户角色判断权限
const userRole = computed(() => userStore.userInfo?.role || '0')
const isAdmin = computed(() => userRole.value === '1' || userRole.value === '2')

// 根据角色决定标题和功能
const pageTitle = computed(() => isAdmin.value ? '申诉管理' : '我的申诉')

// 标签页和分页相关
const activeTab = ref('records')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const appealRecords = ref([])

// 申诉表单相关
const appealFormRef = ref()
const appealForm = reactive({
  violation_id: '',
  reason: '',
  file: ''
})

const rules = reactive({
  violation_id: [{ required: true, message: '请选择违法记录', trigger: 'change' }],
  reason: [{ required: true, message: '请输入申诉理由', trigger: 'blur' }],
  file: [{ required: true, message: '请上传申诉材料', trigger: 'change' }]
})

// 违法记录选项
const violationOptions = ref([])
const selectedViolation = ref({})

// 详情对话框
const detailDialogVisible = ref(false)
const currentAppeal = ref({})

// 处理申诉相关
const processDialogVisible = ref(false)
const processType = ref('') // 'approve' 或 'reject'
const processForm = reactive({
  id: '',
  status: '',
  detail: ''
})

// 获取申诉记录
const fetchAppealRecords = async () => {
  loading.value = true
  try {
    // 根据角色调用不同的API
    const response = isAdmin.value 
      ? await getAppealPage({
          page: currentPage.value,
          pageSize: pageSize.value
        })
      : await getUserAppealPage({
          page: currentPage.value,
          pageSize: pageSize.value
        })
    
    appealRecords.value = response.data.records
    console.log('获取的申诉记录:',response.data.records)
    total.value = response.data.total
  } catch (error) {
    console.error('获取申诉记录失败:', error)
    ElMessage.error('获取申诉记录失败')
  } finally {
    loading.value = false
  }
}

// 获取违法记录选项
const fetchViolationOptions = async () => {
  try {
    const response = await getViolationPage({
      page: 1,  // 添加页码参数
      pageSize: 100,  // 添加每页数量参数，设置较大值以获取所有记录
      status: '0'  // 只获取未处理的违法记录
    }, false) // 获取个人违法记录
    
    console.log('获取的违法记录选项:', response.data)
    if (response.code === 200) {
      violationOptions.value = response.data.records
      console.log('设置的违法记录选项:', violationOptions.value)
    } else {
      ElMessage.error(response.msg || '获取违法记录失败')
    }
  } catch (error) {
    console.error('获取违法记录失败:', error)
    ElMessage.error('获取违法记录失败')
  }
}

// 违法类型相关方法
const getViolationTypeName = (type) => {
  // 尝试将type转换为数字
  const numType = parseInt(type);
  const typeMap = {
    1: '超速',
    2: '未按导向行驶', 
    3: '车辆压线',
    4: '车辆闯红灯',
    5: '行人闯红灯'
  }
  return typeMap[numType] || '其他'
}

const getViolationTypeTag = (type) => {
  const tagMap = {
    1: 'danger',
    2: 'warning',
    3: 'primary',
    4: 'info',
    5: 'success',
  
  }
  return tagMap[type] || 'info'
}

// 状态相关方法
const getStatusName = (status) => {
  const statusMap = {
    '0': '待审核',
    '1': '已通过',
    '2': '已驳回'
  }
  return statusMap[status] || '未知'
}

const getStatusTag = (status) => {
  const tagMap = {
    '0': 'info',
    '1': 'success',
    '2': 'danger'
  }
  return tagMap[status] || ''
}

// 处理违法记录选择变化
const handleViolationChange = (id) => {
  console.log('选择的违法记录ID:', id);
  const selected = violationOptions.value.find(item => item.id === id);
  if (selected) {
    console.log('找到的违法记录:', selected);
    selectedViolation.value = selected;
    // 确保 violation_id 被正确设置
    appealForm.violation_id = id;
  } else {
    console.error('未找到对应的违法记录');
  }
}

// 处理上传成功
const handleUploadSuccess = (response, file) => {
  ElMessage.success('上传成功')
  // 假设后端返回的是文件路径
  if (appealForm.file) {
    appealForm.file += ',' + response.data
  } else {
    appealForm.file = response.data
  }
}

// 处理上传失败
const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isJPG && !isPNG && !isPDF) {
    ElMessage.error('上传文件只能是 JPG/PNG/PDF 格式!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 解析文件路径
const parseFiles = (fileStr) => {
  if (!fileStr) return []
  return fileStr.split(',')
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAppealRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppealRecords()
}

// 查看详情
const handleViewDetail = (row) => {
  currentAppeal.value = row
  detailDialogVisible.value = true
}

// 创建申诉
const handleCreateAppeal = () => {
  activeTab.value = 'create'
}

// 提交申诉
const submitAppealForm = async () => {
  if (!appealFormRef.value) return
  
  try {
    await appealFormRef.value.validate()
    
    await submitAppeal({
      violation_id: appealForm.violation_id,
      reason: appealForm.reason,
      file: appealForm.file
    })
    
    ElMessage.success('申诉提交成功')
    resetForm()
    activeTab.value = 'records'
    fetchAppealRecords()
  } catch (error) {
    console.error('提交申诉失败:', error)
    ElMessage.error('提交申诉失败')
  }
}

// 重置表单
const resetForm = () => {
  if (appealFormRef.value) {
    appealFormRef.value.resetFields()
  }
  selectedViolation.value = {}
}

// 管理员处理申诉 - 通过
const handleApprove = (row) => {
  processType.value = 'approve'
  processForm.id = row.id
  processForm.status = '1' // 已通过
  processForm.detail = ''
  processDialogVisible.value = true
}

// 管理员处理申诉 - 驳回
const handleReject = (row) => {
  processType.value = 'reject'
  processForm.id = row.id
  processForm.status = '2' // 已驳回
  processForm.detail = ''
  processDialogVisible.value = true
}

// 提交处理结果
const submitProcess = async () => {
  try {
    await processAppeal({
      id: processForm.id,
      status: processForm.status,
      detail: processForm.detail
    })
    
    ElMessage.success(processType.value === 'approve' ? '申诉已通过' : '申诉已驳回')
    processDialogVisible.value = false
    fetchAppealRecords()
  } catch (error) {
    console.error('处理申诉失败:', error)
    ElMessage.error('处理申诉失败')
  }
}

onMounted(() => {
  fetchAppealRecords()
  if (!isAdmin.value) {
    fetchViolationOptions()
  }
})
</script>

<style scoped>
.appeal-container {
  padding: 20px;
}

.appeal-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.appeal-files {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.appeal-file-image {
  width: 150px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

.appeal-upload {
  width: 100%;
}
</style>
